package com.tanhua.sso.service;

import com.tanhua.sso.config.HuyiSMSConfig;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;

/*
 * 通过互亿接口：发送短信验证码
 *
 * */
@Slf4j
@Service
public class SmsService {

    @Autowired
    private HuyiSMSConfig config;


    /**
     * redis模板对象：
     */
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    public Integer sendMsg(String mobile) {   // 返回发送的短信验证码

        /*HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(this.config.getUrl());

        client.getParams().setContentCharset("GBK");
        method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=GBK");

        int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);
        String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");

        NameValuePair[] data = {//提交短信
                new NameValuePair("account", config.getAccount()), //查看用户名是登录用户中心->验证码短信->产品总览->APIID
                new NameValuePair("password", config.getPassword()),  //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
                //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
                new NameValuePair("mobile", mobile),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);

        try {
            client.executeMethod(method);

            String SubmitResult = method.getResponseBodyAsString();

            //System.out.println(SubmitResult);

            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();

            String code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");

            System.out.println(code);
            System.out.println(msg);
            System.out.println(smsid);

            if ("2".equals(code)) {
                System.out.println("短信提交成功");
                log.info("发送状态码：" + code + ",提交状态：" + msg + ",信息id：" + smsid);
                return mobile_code;
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("【互亿短信发送失败】" + e);
        }
        return null;*/

        log.info("要发送的电话号码：" + mobile);
        return  123456;            //测试验证码！
    }


    /**
     * 发送短信验证码：需要将短信验证码保存redis!
     * @param phone
     * @return
     */
    public ErrorResult sendCheckMsg(String phone) {
        //判断手机发送的验证码是否还未失效:
        String redisKey = "CHECK_CODE" + phone;   //设置redis的key ,值为接收的短信验证码
        if (this.redisTemplate.hasKey(redisKey)) {    //redis 层判断是否存在key:
            //如果未失效：
            String msg = "上次发送的验证码还未失效！";
            return ErrorResult.builder().errCode("000001").errMessage(msg).build();
        }

        Integer code = sendMsg(phone);
        if (StringUtils.isEmpty(code)){
            String msg = "发送短信验证码失败！";
            return ErrorResult.builder().errCode("000000").errMessage(msg).build();
        }

        //短信发送成功：将验证吗保存redis:
        this.redisTemplate.opsForValue().set(redisKey, code.toString(), Duration.ofMinutes(5));
        return null;
    }
}
